package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entiry.Brand;
import cn.tedu.csmall.product.pojo.entiry.BrandCategory;
import cn.tedu.csmall.product.pojo.entiry.Spu;
import cn.tedu.csmall.product.pojo.param.BrandAddNewParam;
import cn.tedu.csmall.product.pojo.param.BrandUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVO;
import cn.tedu.csmall.product.service.IBrandService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class BrandServiceImpl implements IBrandService {

    @Value("${csmall.crud.default-query-page-size}")
    private int defaultQueryPageSize;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private SpuMapper spuMapper;

    @Override
    public void addNewBrand(BrandAddNewParam brandAddNewParam) {
        log.debug("开始处理【添加品牌】业务，参数：{}", brandAddNewParam);

        // 检查品牌名称是否存在，被占用则抛出异常
        QueryWrapper<Brand> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name", brandAddNewParam.getName());
        Integer countByName = brandMapper.selectCount(queryWrapper1);
        if (countByName > 0) {
            String message = "新增品牌失败，名称已被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //将品牌数据写入到数据库
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandAddNewParam, brand);
        brand.setSales(0);
        brand.setProductCount(0);
        brand.setCommentCount(0);
        brand.setPositiveCommentCount(0);
        brand.setGmtCreate(LocalDateTime.now());
        brand.setGmtModified(LocalDateTime.now());
        int rows = brandMapper.insert(brand);
        if (rows != 1) {
            String message = "添加品牌失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的品牌数据写入到数据库，完成！");

    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据id删除品牌】业务，参数：{}", id);

        // 检查品牌是否存在,若不存在,则抛出异常
        QueryWrapper<Brand> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", id);
        Integer countById = brandMapper.selectCount(queryWrapper1);
        if (countById == 0) {
            String message = "删除品牌失败,品牌数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查是否关联了品牌类别,若关联,则不允许删除
        QueryWrapper<BrandCategory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("brand_id", id);
        Integer countByBrandCategoryBrandId = brandCategoryMapper.selectCount(queryWrapper2);
        if (countByBrandCategoryBrandId > 0) {
            String message = "删除品牌失败,仍有品牌类别关联了此品牌!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 检查是否关联了SPU,若关联,则不允许删除
        QueryWrapper<Spu> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("brand_id", id);
        Integer countBySpuBrandId = spuMapper.selectCount(queryWrapper3);
        if (countBySpuBrandId > 0) {
            String message = "删除品牌失败,仍有SPU关联了此品牌!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行删除
        int rows = brandMapper.deleteById(id);
        if (rows != 1) {
            String message = "根据ID删除品牌失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("根据ID删除品牌,完成！");
    }

    @Override
    public void updateEnable(Long id) {
        log.debug("开始处理【启用品牌】业务，参数ID：{}", id);
        updateEnableById(id,1);
    }

    @Override
    public void updateDisable(Long id) {
        log.debug("开始处理【禁用品牌】业务，参数ID：{}", id);
        updateEnableById(id,0);
    }

    @Override
    public void update(Long id, BrandUpdateInfoParam brandUpdateInfoParam) {
        log.debug("开始处理【根据id修改品牌详情】业务，参数：{}", id);

        // 检查品牌是否存在，若不存在则抛出异常
        QueryWrapper<Brand> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", id);
        Integer countById = brandMapper.selectCount(queryWrapper1);
        if (countById == 0) {
            String message = "修改品牌详情失败，品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查名称是否已被占用，若被占用则抛出异常
        // 名称相同，id不同算被占用
        QueryWrapper<Brand> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("name", brandUpdateInfoParam.getName())
                .ne("id", id);
        Integer countByNameAndId = brandMapper.selectCount(queryWrapper2);
        if (countByNameAndId > 0) {
            String message = "修改品牌详情失败，名称已被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行修改
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandUpdateInfoParam, brand);
        brand.setId(id);
        int rows = brandMapper.updateById(brand);
        if (rows != 1) {
            String message = "修改品牌详情失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据id获取品牌详情】业务，参数：{}", id);

        // 查询品牌是否存在，不存在则抛出异常
        BrandStandardVO standard = brandMapper.getStandard(id);
        if (standard == null) {
            String message = "查询品牌失败，品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("查询id为{}的品牌完成！", id);
        return standard;
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNo) {
        log.debug("开始处理【获取品牌列表】业务，页码：{}", pageNo);

        return list(pageNo, defaultQueryPageSize);
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNo, Integer pageSize) {
        log.debug("开始处理【获取品牌列表】业务，页码：{}，每页数据量：{}", pageNo, pageSize);

        PageHelper.startPage(pageNo, pageSize);
        List<BrandListItemVO> list = brandMapper.list();
        PageInfo<BrandListItemVO> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverter.convert(pageInfo);
    }

    private void updateEnableById(Long id, Integer enable) {

        // 查询品牌是否存在，不存在则抛出异常
        BrandStandardVO standardById = brandMapper.getStandard(id);
        if (standardById == null) {
            String message = ENABLE_text[enable] + "类别失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

       // 判断查询结果中的enable与参数enable是否相同，如果是，则抛出异常（当前状态与目标状态相同，没必要执行更新）
        if (standardById.getEnable() == enable) {
            String message = ENABLE_text[enable] + "类别失败，类别已经是" + ENABLE_text[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行修改
        Brand brand = new Brand();
        brand.setId(id);
        brand.setEnable(enable);
        int rows = brandMapper.updateById(brand);
        if (rows != 1) {
            String message = ENABLE_text[enable] + "类别失败，服务器正忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("{}类别完成！", ENABLE_text[enable]);
    }
}
